var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var app = express();

const joi = require('joi')
// 导入 cors 中间件
const cors = require('cors')
// 将 cors 注册为全局中间件
app.use(cors())

// 引入全局路由
var indexRouter = require('./routes/index');
var userLogin = require('./routes/login');
var userRegister = require('./routes/register')
var usersRouter = require('./routes/users');
var majorCate = require('./routes/majorcate')
var majors = require('./routes/majors')
var articles = require('./routes/articles')
var userContent = require('./routes/content');
var userSetting = require('./routes/setting');
var userEdit = require('./routes/edit');
// var userHtml = require('./routes/html');
var addcomment = require('./routes/comment');

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));


// 在路由之前，封装调用响应中间件
app.use((req, res, next)=> {
  // status=1，表示默认错误
  res.show = (err, status = 1) =>{
    res.send({
      status,
      message: err instanceof Error ? err.message : err,
    })
  }
  next()
})

// 在路由之前配置解析 Token 的中间件
const expressJWT = require('express-jwt')
const config = require('./config')
app.use(
  expressJWT({
    secret: config.jwtSecretKey,
    algorithms: ["HS256"],
    // 无token请求不进行解析，并且抛出异常
    credentialsRequired: false,
  }).unless({
    path: [
      "/login",
      "/register",
      "/index",
      { url: /^\/articles\/.*/, methods: ["GET"] },
      { url: /^\/content\/.*/, methods: ["GET"] },
    ],
  })
);


// 注册全局路由
app.use('/index', indexRouter);
app.use('/login', userLogin);
app.use('/register', userRegister);
app.use('/content', userContent);
app.use("/articles", articles);
app.use('/my/setting',userSetting);
app.use('/my/users', usersRouter);
app.use('/my/majorcate', majorCate);
app.use('/my/majors', majors);
app.use('/my/addcomment', addcomment);

app.use("/my/edit",userEdit);
// app.use("/test",(req,res) => {
//   res.render('pages/test')
// });

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

//定义错误级别中间件
app.use((err, req, res, next) => {
  // 数据验证错误
  if(err instanceof joi.ValidationError) return res.show(err)
  // Token 认证失败
  if(err.name === 'UnauthorizedError') return res.show('身份认证失败！')
  // 未知错误
  res.show(err)

  next()
})


// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');

});


module.exports = app;
